#!/bin/bash

# ANSI 转义序列定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'  # 重置颜色

# 日志函数
log() {
    local level="$1"
    local message="$2"
    case "$level" in
        "INFO")
            echo -e "${GREEN}ℹ️ $message${NC}"
            ;;
        "WARNING")
            echo -e "${YELLOW}⚠️ $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}❌ $message${NC}"
            ;;
        *)
            echo -e "$message"
            ;;
    esac
}

# 查找项目根目录
find_project_root() {
    local current_dir=$(pwd)
    while true; do
        if [[ -f "$current_dir/manage.py" || -d "$current_dir/.git" ]]; then
            echo "$current_dir"
            return
        fi
        local parent_dir=$(dirname "$current_dir")
        if [[ "$parent_dir" == "$current_dir" ]]; then
            echo "$current_dir"
            return
        fi
        current_dir="$parent_dir"
    done
}

# 获取项目名称
get_project_name() {
    local project_root=$(find_project_root)
    basename "$project_root"
}

# 创建虚拟环境
create_venv() {
    local envs_root="/envs"
    local project_name=$(get_project_name)
    local venv_path="$envs_root/$project_name"
    local new_python="/usr/local/python3.9/bin/python3"

    # 创建 envs 目录（带权限设置）
    if [[ ! -d "$envs_root" ]]; then
        log "INFO" "创建 envs 目录..."
        sudo mkdir -p "$envs_root"
        sudo chmod 755 "$envs_root"  # 设置合理权限
    fi

    # 检查虚拟环境是否存在
    if [[ -d "$venv_path" ]]; then
        log "WARNING" "虚拟环境已存在，先删除旧环境"
        rm -rf "$venv_path"
    fi

    # 创建虚拟环境并严格校验
    log "INFO" "创建虚拟环境（使用新 Python）..."
    "$new_python" -m venv "$venv_path" || {
        log "ERROR" "虚拟环境创建失败，请检查新 Python 路径"
        exit 1
    }
    
    # 检查虚拟环境是否创建成功
    if [[ ! -f "$venv_path/bin/activate" ]]; then
        log "ERROR" "虚拟环境创建失败，激活文件不存在"
        exit 1
    fi
    log "INFO" "虚拟环境已创建: $venv_path"
    
    # 激活虚拟环境
    log "INFO" "激活虚拟环境..."
    source "$venv_path/bin/activate"
    log "INFO" "虚拟环境激活成功，当前路径：$venv_path"

    # 配置别名和补全规则
    configure_alias "$project_name" "$venv_path"
}

# 配置别名和补全规则
configure_alias() {
    local project_name="$1"
    local venv_path="$2"
    local activate_cmd="source $venv_path/bin/activate"
    local bashrc="$HOME/.bashrc"

    # 添加别名（带去重处理）
    if ! grep -q "alias $project_name=" "$bashrc"; then
        echo -e "\nalias $project_name='$activate_cmd'" >> "$bashrc"
    else
        log "INFO" "别名已存在，跳过添加"
    fi

    # 添加补全规则（带去重处理）
    local completion_rule="complete -F _venv_complete $project_name"
    if ! grep -q "$completion_rule" "$bashrc"; then
        echo -e "\n# 虚拟环境补全 - $project_name" >> "$bashrc"
        echo "_venv_complete() {" >> "$bashrc"
        echo "    local cur=\${COMP_WORDS[COMP_CWORD]}" >> "$bashrc"
        echo "    COMPREPLY=( \$(compgen -W \"\$(ls /envs | grep -E '^[a-zA-Z0-9_-]+$')\" -- \$cur) )" >> "$bashrc"
        echo "}" >> "$bashrc"
        echo "$completion_rule" >> "$bashrc"
    else
        log "INFO" "补全规则已存在，跳过添加"
    fi

    # 重新加载 .bashrc
    source "$bashrc"
    log "INFO" "别名已设置: $project_name"
    echo "使用方法: $project_name （输入首字母按 Tab 补全）"
    log "INFO" "当前虚拟环境路径: $venv_path"
}

# 主执行逻辑
create_venv
project_name=$(get_project_name)
echo -e "\n🎉 所有操作完成，立即生效："
echo "  激活环境: $project_name"
echo "  Tab 补全: 输入 '${project_name:0:1}' 后按 Tab 查看所有别名"